package com.jingxi.service;
import com.jingxi.common.pojo.IDUtils;
import com.jingxi.common.util.FtpUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.Map;

@Service
public class ImageUploadServiceImpl implements ImageUploadService {
    @Value("${FTP_SERVER_IP}")
    private String FTP_SERVER_IP;
    @Value("${FTP_SERVER_PORT}")
    private int FTP_SERVER_PORT;
    @Value("${FTP_SERVER_USERNAME}")
    private String FTP_SERVER_USERNAME;
    @Value("${FTP_SERVER_PASSWORD}")
    private String FTP_SERVER_PASSWORD;

    @Value("${FILE_UPLOAD_PATH}")
    private String FILE_UPLOAD_PATH;
    @Value("${IMAGE_BASE_URL}")
    private String IMAGE_BASE_URL;

    @SuppressWarnings({"uncheked", "rawtypes"})
    @Override
    public Map uploadFile(MultipartFile multipartFile) throws Exception {
        Map resultMap = new HashMap();
        try {
            if (multipartFile.isEmpty()) {
                return null;

            }
            String filepath = new DateTime().toString("/yyyy/mm/dd");
            String FileName = multipartFile.getOriginalFilename();
            String newFileName = IDUtils.genImageName() + FileName.substring(FileName.lastIndexOf("."));
            Boolean isSuccessed = FtpUtil.uploadFile(FTP_SERVER_IP, FTP_SERVER_PORT, FTP_SERVER_USERNAME,
                    FTP_SERVER_PASSWORD, FILE_UPLOAD_PATH, filepath, newFileName, multipartFile.getInputStream()
            );
            String path = filepath + "/" + newFileName;
            if (isSuccessed) {
                resultMap.put("error", 0);
                resultMap.put("url", IMAGE_BASE_URL + path);
                System.out.println("url:{}"+IMAGE_BASE_URL + path);
            } else {
                resultMap.put("error", 1);
                resultMap.put("message", "文件上传失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }
}
